<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <style>
        .highlight {
            background-color: #fff8e1;
            font-weight: bold;
            padding: 2px 4px;
            border-radius: 3px;
        }

        /* 添加搜索容器样式 */
        .search-container {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
            flex-wrap: wrap;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        h1 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 24px;
            font-weight: 600;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .search-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: center;
        }

        .search-input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            max-width: 300px;
        }

        .btn-back {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-back:hover {
            background-color: #2980b9;
            text-decoration: none;
        }

        .btn-back i {
            font-size: 12px;
        }

        .search-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        .search-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .search-btn:hover {
            background-color: #2980b9;
        }

        .clear-btn {
            background-color: #95a5a6;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .clear-btn:hover {
            background-color: #7f8c8d;
        }

        .search-stats {
            margin-left: auto;
            color: #7f8c8d;
            font-size: 14px;
        }

        .btn-add {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 20px;
        }

        .btn-add:hover {
            background-color: #27ae60;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th {
            background-color: #3498db;
            color: white;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
        }

        td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
        }

        tr:hover {
            background-color: #f8f9fa;
        }


        .highlight {
            background-color: #fff8e1;
            font-weight: bold;
        }

        .btn-edit {
            background-color: #f39c12;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 3px;
            cursor: pointer;
            margin-right: 5px;
        }

        .btn-edit:hover {
            background-color: #e67e22;
        }

        .btn-delete {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 3px;
            cursor: pointer;
        }

        .btn-delete:hover {
            background-color: #c0392b;
        }

        /* 模态框样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            min-width: 400px;
        }

        .modal h2 {
            margin-bottom: 20px;
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-actions {
            margin-top: 20px;
            text-align: right;
        }

        .btn-submit {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-submit:hover {
            background-color: #2980b9;
        }

        .btn-cancel {
            background-color: #95a5a6;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        .btn-cancel:hover {
            background-color: #7f8c8d;
        }

        /* 错误提示框样式 */
        .error-modal {
            text-align: center;
        }

        .error-message {
            color: #e74c3c;
            font-size: 16px;
            margin: 20px 0;
        }

        .btn-ok {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 30px;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="header">
        <h1>用户管理</h1>
        <div class="header-actions">
            <a class="btn-back" href="/interview">
                <i class="fas fa-arrow-left"></i>返回简历分析
            </a>
        </div>
    </div>
    <button class="btn-add" onclick="showAddModal()">增加用户</button>
    <!-- 搜索功能 -->
    <div class="search-container">
        <input class="search-input" id="searchInput" placeholder="输入用户名或邮箱进行搜索..." type="text">
        <button class="search-btn" onclick="performSearch()">搜索</button>
        <button class="clear-btn" onclick="clearSearch()">清除</button>
        <div class="search-stats" id="searchStats">显示 <span id="filteredCount">4</span> 个用户，共 <span
                id="totalCount">4</span> 个用户
        </div>
    </div>

    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="userTableBody">
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.username}"></td>
            <td th:text="${user.email ?: '未设置'}"></td>
            <td>
                <button class="btn-edit" onclick="editUser(this)" th:data-id="${user.id}">编辑</button>
                <button class="btn-delete" onclick="deleteUser(this)" th:data-id="${user.id}">删除</button>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<!-- 模态框代码保持不变 -->
<!-- 增加用户模态框 -->
<div class="modal-overlay" id="addModal">
    <div class="modal">
        <h2>增加用户</h2>
        <form id="addForm">
            <div class="form-group">
                <label for="addUsername">用户名</label>
                <input id="addUsername" name="username" required type="text">
            </div>
            <div class="form-group">
                <label for="addEmail">邮箱</label>
                <input id="addEmail" name="email" required type="email">
            </div>
            <div class="form-group">
                <label for="addPassword">密码</label>
                <input id="addPassword" name="password" required type="password">
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeModal('addModal')" type="button">取消</button>
                <button class="btn-submit" type="submit">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal-overlay" id="editModal">
    <div class="modal">
        <h2>编辑用户</h2>
        <form id="editForm">
            <input id="editId" name="id" type="hidden">
            <div class="form-group">
                <label for="editUsername">用户名</label>
                <input id="editUsername" name="username" required type="text">
            </div>
            <div class="form-group">
                <label for="editEmail">邮箱</label>
                <input id="editEmail" name="email" required type="email">
            </div>
            <div class="form-group">
                <label for="editPassword">密码 (留空不修改)</label>
                <input id="editPassword" name="password" type="password">
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeModal('editModal')" type="button">取消</button>
                <button class="btn-submit" type="submit">更新</button>
            </div>
        </form>
    </div>
</div>

<!-- 错误提示模态框 -->
<div class="modal-overlay" id="errorModal">
    <div class="modal error-modal">
        <h2>操作失败</h2>
        <div class="error-message" id="errorMessage"></div>
        <button class="btn-ok" onclick="closeModal('errorModal')">确定</button>
    </div>
</div>

<script>
    // 存储原始用户数据
    let originalUsers = [];
    let isSearchActive = false;

    // ====== 登录功能 ======
    function handleLoginSuccess(data) {
        if (data.token && data.user) {
            localStorage.setItem('authToken', data.token);
            localStorage.setItem('user', JSON.stringify(data.user));
            
            // 重定向到当前页面或默认页面
            window.location.href = window.location.href;
        }
    }

    // ====== 用户状态管理 ======
    function checkLoginStatus() {
        const token = localStorage.getItem('authToken');
        const user = localStorage.getItem('user');

        // 如果没有token，重定向到登录页面
        if (!token) {
            showUnauthenticatedState();
            return;
        }

        // 验证Token并获取最新用户信息
        fetch('/api/auth/me', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                if (response.ok) {
                    return response.json();
                }
                if (response.status === 401) {
                    throw new Error('登录已过期');
                }
                throw new Error('获取用户信息失败');
            })
            .then(data => {
                if (data.username) {
                    localStorage.setItem('user', JSON.stringify(data));
                }
            })
            .catch(error => {
                console.error('用户状态检查失败:', error);
                showUnauthenticatedState();
            });
    }

    function showUnauthenticatedState() {
        // 清除本地存储
        localStorage.removeItem('authToken');
        localStorage.removeItem('user');
        
        // 重定向到登录页面，并带上当前页面作为重定向参数
        window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
    }

    // 使用认证的fetch方法
    function fetchWithAuth(url, options = {}) {
        const token = localStorage.getItem('authToken');
        if (!token) {
            showUnauthenticatedState();
            return Promise.reject('未登录');
        }

        return fetch(url, {
            ...options,
            headers: {
                ...options.headers,
                'Authorization': `Bearer ${token}`
            }
        }).catch(error => {
            console.error('API调用失败:', error);
            // 可以在这里添加错误处理逻辑
        });
    }

    // ====== 页面功能初始化 ======
    document.addEventListener('DOMContentLoaded', function () {
        // 首先检查登录状态
        checkLoginStatus();
        
        // 然后初始化页面数据
        console.log('页面加载完成，初始化用户数据');

        // 保存原始用户数据
        const rows = document.querySelectorAll('#userTableBody tr');
        originalUsers = Array.from(rows).map(row => {
            return {
                id: row.querySelector('td:nth-child(1)').textContent,
                username: row.querySelector('td:nth-child(2)').textContent,
                email: row.querySelector('td:nth-child(3)').textContent,
                element: row
            };
        });

        // 初始化事件绑定
        bindButtonEvents();

        // 立即更新搜索统计
        updateSearchStats(originalUsers.length, originalUsers.length);

        console.log('初始化完成，用户数量:', originalUsers.length);
    });

    // 绑定按钮事件（修复后的版本）
    function bindButtonEvents() {
        console.log('绑定按钮事件');

        // 移除所有现有的事件监听器
        document.querySelectorAll('.btn-edit').forEach(button => {
            button.onclick = null; // 清除旧的事件
            button.onclick = function () {
                editUser(this);
            };
        });

        document.querySelectorAll('.btn-delete').forEach(button => {
            button.onclick = null; // 清除旧的事件
            button.onclick = function () {
                deleteUser(this);
            };
        });
    }

    // 搜索功能
    function performSearch() {
        const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
        const tbody = document.getElementById('userTableBody');

        if (!searchTerm) {
            // 如果搜索词为空，恢复原始显示
            restoreOriginalDisplay();
            return;
        }

        isSearchActive = true;

        // 使用filter进行模糊搜索
        const filteredUsers = originalUsers.filter(user => {
            return user.username.toLowerCase().includes(searchTerm) ||
                user.email.toLowerCase().includes(searchTerm);
        });

        // 先隐藏所有行
        originalUsers.forEach(user => {
            user.element.style.display = 'none';
        });

        // 显示匹配的行并添加高亮
        filteredUsers.forEach(user => {
            user.element.style.display = '';

            // 高亮匹配的文本
            const usernameCell = user.element.querySelector('td:nth-child(2)');
            const emailCell = user.element.querySelector('td:nth-child(3)');

            usernameCell.innerHTML = highlightText(user.username, searchTerm);
            emailCell.innerHTML = highlightText(user.email, searchTerm);
        });

        // 重新绑定事件（确保按钮正常工作）
        bindButtonEvents();

        updateSearchStats(filteredUsers.length, originalUsers.length);
    }

    // 恢复原始显示
    function restoreOriginalDisplay() {
        console.log('恢复原始显示');
        isSearchActive = false;

        // 恢复所有行的显示
        originalUsers.forEach(user => {
            user.element.style.display = '';

            // 恢复原始文本内容（移除高亮）
            const usernameCell = user.element.querySelector('td:nth-child(2)');
            const emailCell = user.element.querySelector('td:nth-child(3)');

            usernameCell.textContent = user.username;
            emailCell.textContent = user.email;
        });

        // 重新绑定事件
        bindButtonEvents();

        updateSearchStats(originalUsers.length, originalUsers.length);
    }

    // 清除搜索
    function clearSearch() {
        console.log('清除搜索');
        document.getElementById('searchInput').value = '';
        restoreOriginalDisplay();
    }

    // 高亮文本
    function highlightText(text, searchTerm) {
        if (!text || !searchTerm) return text;

        const regex = new RegExp(`(${searchTerm})`, 'gi');
        return text.replace(regex, '<span class="highlight">$1</span>');
    }

    // 更新搜索统计
    function updateSearchStats(filteredCount, totalCount) {
        document.getElementById('filteredCount').textContent = filteredCount;
        document.getElementById('totalCount').textContent = totalCount;
    }

    // 模态框控制函数
    function showAddModal() {
        document.getElementById('addModal').style.display = 'block';
        document.getElementById('addForm').reset();
    }

    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }

    // 编辑用户函数
    function editUser(button) {
        const userId = button.getAttribute('data-id');
        console.log('正在获取用户ID:', userId);

        fetchWithAuth(`/admin/edit-user?id=${userId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误 ${response.status}`);
                }
                return response.json();
            })
            .then(user => {
                document.getElementById('editId').value = user.id;
                document.getElementById('editUsername').value = user.username;
                document.getElementById('editEmail').value = user.email || '';
                document.getElementById('editPassword').value = '';
                document.getElementById('editModal').style.display = 'block';
            })
            .catch(error => {
                showError('获取用户信息失败: ' + error.message);
            });
    }

    // 删除用户函数
    function deleteUser(button) {
        const userId = button.getAttribute('data-id');

        if (confirm('确定要删除该用户吗？')) {
            fetchWithAuth(`/admin/delete-user/${userId}`, {
                method: 'GET'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    return response.text();
                })
                .then(message => {
                    alert(message);
                    location.reload();
                })
                .catch(error => {
                    showError('删除用户失败: ' + error.message);
                });
        }
    }

    // 显示错误信息
    function showError(message) {
        document.getElementById('errorMessage').textContent = message;
        document.getElementById('errorModal').style.display = 'block';
    }

    // 表单提交处理
    document.getElementById('addForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const userData = Object.fromEntries(formData.entries());

        fetchWithAuth('/admin/add-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加失败');
                }
                return response.text();
            })
            .then(message => {
                alert(message);
                closeModal('addModal');
                location.reload();
            })
            .catch(error => {
                showError('添加用户失败: ' + error.message);
            });
    });

    document.getElementById('editForm').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const userData = Object.fromEntries(formData.entries());

        fetchWithAuth('/admin/edit-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('更新失败');
                }
                return response.text();
            })
            .then(message => {
                alert(message);
                closeModal('editModal');
                location.reload();
            })
            .catch(error => {
                showError('更新用户失败: ' + error.message);
            });
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function (e) {
        if (e.target.classList.contains('modal-overlay')) {
            e.target.style.display = 'none';
        }
    });
</script>
</body>
</html>